package com.hqq.redis.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * Redist相关配置类
 * @author huangqiqin
 * @date 2021/03/21 13:13
 **/
@Configuration
public class RedisConfig {

    /**
     * Redis连接工厂
     */
    @Autowired
    private RedisConnectionFactory redisConnectionFactory;

    /**
     * 构建RedisTemplate对象并注入到spring容器中
     * @return
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(){
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();

        // 设置redis连接工厂
        redisTemplate.setConnectionFactory(this.redisConnectionFactory);
        // 指定key的序列化策略为String
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        // 指定value的序列化策略为JDK自带的序列化策略
        redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
        // 指定hashKey的序列化策略为String序列化（针对hash数据结构的存储）
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());

        return redisTemplate;
    }

    /**
     * 构建StringRedisTemplate对象并注入到Spring容器中
     * @return
     */
    @Bean
    public StringRedisTemplate stringRedisTemplate(){
        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
        // 使用默认配置即可
        stringRedisTemplate.setConnectionFactory(this.redisConnectionFactory);
        return stringRedisTemplate;
    }
}
